import React, { useEffect, useState, useCallback } from 'react';
import { connect } from 'dva';
import { Table, Pagination, Button, message, Popconfirm, Form, Input } from 'antd';
import { AdminModelState } from '@/models/admin';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import './index.less'; // 引入样式文件

// 表格的列配置
const columns = (handleDelete: (id: number) => void, handleUpdate: (record: any) => void) => [
    {
        title: 'Username',
        dataIndex: 'username',
        key: 'username',
    },
    {
        title: 'Display Name',
        dataIndex: 'display_name',
        key: 'display_name',
    },
    {
        title: 'Create Time',
        dataIndex: 'create_time',
        key: 'create_time',
    },
    {
        title: 'Status',
        dataIndex: 'status',
        key: 'status',
        render: (status: number) => (status === 1 ? 'Enabled' : 'Disabled'),
    },
    {
        title: 'Action',
        key: 'action',
        render: (text: string, record: any) => (
            <>
                <Button type="link" onClick={() => handleUpdate(record)}>
                    编辑
                </Button>
                <Popconfirm
                    title="确定删除吗？"
                    onConfirm={() => handleDelete(record.id)}
                    okText="确定"
                    cancelText="取消"
                >
                    <Button type="link" danger>
                        删除
                    </Button>
                </Popconfirm>
            </>
        ),
    },
];

const ListPage = ({ dispatch, admin }: { dispatch: any; admin: AdminModelState }) => {
    const { list, total, currentPage, pageSize, searchParams } = admin;
    const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
    const [createModalVisible, setCreateModalVisible] = useState(false);
    const [updateModalVisible, setUpdateModalVisible] = useState(false);
    const [currentRecord, setCurrentRecord] = useState<any>(null);
    const [form] = Form.useForm();
    const [localSearchParams, setLocalSearchParams] = useState(searchParams); // 本地查询条件状态

    // 分发请求以获取列表数据
    useEffect(() => {
        dispatch({
            type: 'admin/fetchList',
            payload: {
                page: currentPage,
                pageSize,
                ...localSearchParams, // 使用本地查询参数
            },
        });
    }, [currentPage, pageSize, localSearchParams, dispatch]);

    // 翻页处理
    const handlePageChange = (page: number, pageSize: number) => {
        dispatch({
            type: 'admin/fetchList',
            payload: {
                page,
                pageSize,
                ...localSearchParams, // 保留当前查询条件
            },
        });
    };

    // 查询处理
    const handleSearch = (values: any) => {
        setLocalSearchParams(values); // 更新本地查询条件
        dispatch({
            type: 'admin/fetchList',
            payload: {
                page: 1, // 查询时重置到第一页
                pageSize,
                ...values,
            },
        });
    };

    // 重置查询
    const handleReset = () => {
        form.resetFields();
        setLocalSearchParams({}); // 清空本地查询条件
        dispatch({
            type: 'admin/fetchList',
            payload: {
                page: 1,
                pageSize,
            },
        });
    };

    // 删除单条数据
    const handleDelete = useCallback((id: number) => {
        dispatch({
            type: 'admin/delete',
            payload: id,
        }).then(() => {
            message.success('删除成功');
        });
    }, [dispatch]);

    // 批量删除处理
    const handleBatchDeleteConfirm = () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请选择要删除的项目');
            return;
        }

        dispatch({
            type: 'admin/delete',
            payload: selectedRowKeys,
        }).then(() => {
            message.success('批量删除成功');
            setSelectedRowKeys([]);
        });
    };

    // 创建数据
    const handleCreate = async (values: any) => {
        await dispatch({
            type: 'admin/create',
            payload: values,
        });
        message.success('创建成功');
        setCreateModalVisible(false);
    };

    // 更新数据
    const handleUpdate = async (values: any) => {
        await dispatch({
            type: 'admin/update',
            payload: {
                id: currentRecord.id,
                data: values,
            },
        });
        message.success('更新成功');
        setUpdateModalVisible(false);
    };

    // 表格的行选择配置
    const rowSelection = {
        selectedRowKeys,
        onChange: (keys: React.Key[]) => {
            setSelectedRowKeys(keys as number[]);
        },
    };

    return (
        <div>
            {/* 查询和按钮区域 */}
            <div className="toolbar">
                <div className="button-group">
                    <Button type="primary" style={{ marginLeft: 8 }} onClick={() => setCreateModalVisible(true)}>
                        新建
                    </Button>
                    <Popconfirm
                        title={`确定要删除选中的 ${selectedRowKeys.length} 项吗？`}
                        onConfirm={handleBatchDeleteConfirm}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button
                            type="primary"
                            danger
                            disabled={selectedRowKeys.length === 0}
                            style={{ marginLeft: 8 }}
                        >
                            批量删除
                        </Button>
                    </Popconfirm>
                </div>
                <Form form={form} layout="inline" onFinish={handleSearch}>
                    <Form.Item name="username" label="Username">
                        <Input placeholder="请输入用户名" />
                    </Form.Item>
                    <Form.Item name="display_name" label="Display Name">
                        <Input placeholder="请输入显示名称" />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            查询
                        </Button>
                        <Button style={{ marginLeft: 8 }} onClick={handleReset}>
                            重置
                        </Button>
                    </Form.Item>
                </Form>
            </div>

            <Table
                columns={columns(handleDelete, (record) => {
                    setCurrentRecord(record);
                    setUpdateModalVisible(true);
                })}
                dataSource={list}
                rowKey="id"
                pagination={false}
                rowSelection={rowSelection}
            />
            <Pagination
                current={currentPage}
                pageSize={pageSize}
                total={total}
                onChange={handlePageChange}
                style={{ marginTop: 16, textAlign: 'right' }}
            />

            {/* 创建表单 */}
            <CreateForm
                modalVisible={createModalVisible}
                onCancel={() => setCreateModalVisible(false)}
                onSubmit={handleCreate}
            />

            {/* 更新表单 */}
            {currentRecord && (
                <UpdateForm
                    updateModalVisible={updateModalVisible}
                    onCancel={() => setUpdateModalVisible(false)}
                    onSubmit={handleUpdate}
                    values={currentRecord}
                />
            )}
        </div>
    );
};

export default connect(({ admin }: { admin: AdminModelState }) => ({
    admin,
}))(ListPage);